import { ref, onUnmounted } from 'vue'
import { io } from 'socket.io-client'

// 全局单例 socket 实例
let globalSocket = null
const socketRef = ref(null)
const connectedRef = ref(false)

// 初始化全局 socket
function initGlobalSocket() {
  if (globalSocket?.connected) {
    socketRef.value = globalSocket
    connectedRef.value = true
    console.log('使用已存在的 Socket 连接，ID:', globalSocket.id)
    return globalSocket
  }
  
  if (globalSocket && !globalSocket.connected) {
    // 如果存在但未连接，先断开
    globalSocket.disconnect()
    globalSocket = null
  }
  
  // 获取 API URL（支持环境变量）
  const apiUrl = import.meta.env.VITE_API_URL || window.location.origin
  const socketUrl = apiUrl || 'http://localhost:3000'
  
  // 创建新的 socket 连接
  globalSocket = io(socketUrl)
  socketRef.value = globalSocket
  
  globalSocket.on('connect', () => {
    connectedRef.value = true
    socketRef.value = globalSocket
    console.log('已连接到服务器，Socket ID:', globalSocket.id)
  })

  globalSocket.on('disconnect', () => {
    connectedRef.value = false
    console.log('与服务器断开连接')
  })

  return globalSocket
}

export function useSocket() {
  // 如果全局 socket 已存在，直接使用
  if (globalSocket?.connected) {
    socketRef.value = globalSocket
    connectedRef.value = true
  } else if (!globalSocket) {
    // 如果不存在，初始化
    initGlobalSocket()
  }

  function connect() {
    if (globalSocket?.connected) {
      socketRef.value = globalSocket
      connectedRef.value = true
      console.log('Socket 已连接，ID:', globalSocket.id)
      return globalSocket
    }
    
    return initGlobalSocket()
  }

  function disconnect() {
    if (globalSocket) {
      globalSocket.disconnect()
      globalSocket = null
      socketRef.value = null
      connectedRef.value = false
    }
  }

  // 注意：不在 onUnmounted 中断开，因为可能其他组件还在使用
  // 如果需要完全断开，可以手动调用 disconnect()

  return {
    socket: socketRef,
    connected: connectedRef,
    connect,
    disconnect
  }
}

